package cn.nexttec.noteplayer.service

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.IBinder
import cn.nexttec.noteplayer.common.HTTP
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.common.gson
import cn.nexttec.noteplayer.models.EyeReport
import cn.nexttec.noteplayer.repository.HttpProvider
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class TraceService : Service() {
    @Inject
    lateinit var preference: Preference

    private val job = SupervisorJob()
    private val scope = CoroutineScope(Dispatchers.IO + job)

    companion object {
        fun bindService(
            context: Context,
            onConnected: (TraceService) -> Unit,
            onDisconnected: (() -> Unit)? = null
        ): ServiceConnection? {
            val conn = object : ServiceConnection {
                override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
                    val binder = p1 as LocalBinder
                    onConnected(binder.service)
                }

                override fun onServiceDisconnected(p0: ComponentName?) {
                    onDisconnected?.invoke()
                }

            }
            val intent = Intent(context, TraceService::class.java)
            return if (context.bindService(intent, conn, Context.BIND_AUTO_CREATE))
                conn
            else
                null
        }
    }

    inner class LocalBinder : Binder() {
        val service = this@TraceService
    }

    override fun onBind(intent: Intent): IBinder {
        return LocalBinder()
    }

    fun report(report: EyeReport){
        scope.launch {
            HTTP debug report.gson()
            val response = HttpProvider.service.postTrace(report)
            HTTP debug response.gson()
        }
    }
}